/*
-------------------------------------------------------------------
BIE is Copyright 2001-2004 Brunswick Corp.
-------------------------------------------------------------------
Please read the legal notices (docs/legal.txt) and the license
(docs/bie_license.txt) that came with this distribution before using
this software.
-------------------------------------------------------------------

*/
/*
 * DownloadPOP3Email.java
 *
 * Created on February 13, 2003, 10:40 AM
 */

//package com.webdeninteractive.xbotts.client.serviceproviders;
import java.util.*;
import java.util.Properties;
import java.net.*;
import java.io.*;
import java.lang.*;

import javax.mail.*;
import javax.mail.internet.*;
/**
 *
 * @author  siewean
 */
public class DownloadPOP3Email {
    
    /** Creates a new instance of DownloadPOP3Email */
    private String host = null;
    private String username = null;
    private String password = null;
    private int port = -1;
    
    public DownloadPOP3Email(String host, String username, String password){
        
        this.host = host;
        this.username = username;
        this.password = password;
        
    }//end of constructor
    
    public DownloadPOP3Email(String host, String username, String password, int port){
        
        this.host = host;
        this.username = username;
        this.password = password;
        this.port = port;
        
    }//end of constructor
    
    /* methods to return hostname username password */
    public String host() {
        return host;
    }
    
    public String username() {
        return username;
    }
    
    public String password() {
        return password;
    }
    
    public int port() {
        return port;
    }
    
    private Folder Setup(){
        
        Folder folder = null;
        boolean debug = false;
        
        try {
            
            //Get a properties object
            Properties props = System.getProperties();
            props.put("mail.pop3.message.class","com.sun.mail.pop3.POP3Store");
            
            //Get a Session object
            Session session = Session.getDefaultInstance(props,null);
            session.setDebug(debug);
            
            //Get a Store object
            URLName urln = new URLName("pop3://"+username+":"+password+"@"+host);
            Store store = session.getStore(urln);
            store.connect();
			
			/*Optional method to get Store and connect to POP3
			Store store = session.getStore("pop3");// Get the store
			store.connect(host, username, password);// Connect to store
			*/
            
            //POP3 only has one folder called INBOX			
            folder = store.getFolder("INBOX");
            try {
                folder.open(Folder.READ_WRITE);
            }
            catch (MessagingException ex) {
                folder.open(Folder.READ_ONLY);
            }
            
            folder.close(false);
            store.close();
            
        }//end try
        catch (Exception e) {
            e.printStackTrace();
        }
        
        return folder;
    }//end of Setup
    
	//this method returns all emails body but does not get attachments
	public String[] DownloadAllEmails() {
		String [] emails = DownloadAllEmails(false,null);
		return emails;
	}
	
	//this method returns all emails and retrieve attachments to the home directory given (attachHome)
    public String[] DownloadAllEmails(boolean getAttach, String attachHome) {
        
        Message[] msg = null;
        Folder inbox = Setup();
        String[] msgString = null;
        try {
            
            try {
                inbox.open(Folder.READ_WRITE);
            }
            catch (MessagingException ex) {
                inbox.open(Folder.READ_ONLY);
            }
            
            int totalMessages = inbox.getMessageCount();
			System.out.println("how many emails are there? - "+totalMessages);
            if (totalMessages == 0) {
                inbox.close(false);
                return msgString;
            }
            
            msg = inbox.getMessages();
            msgString = new String[totalMessages];
            for (int i = 0; i< totalMessages; i++){
				System.out.println("now is "+i);
                msgString[i] = GetEmailBody(msg[i]);
            }
			if (getAttach && attachHome != null) {
				for (int z=0, n=msg.length; z<n; z++) {
					System.out.println("here is "+z);
					MimeMessage tempMessage = (MimeMessage)msg[z];
					GetEmailAttachment(tempMessage,attachHome);
				}
			}
            inbox.close(false);
        }//end outer try
        catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return msgString;
    }//end of DownloadAllEmails

	//this method return all email body only
	public String DownloadSingleEmail(int msgNumber) {
		String email = DownloadSingleEmail(msgNumber,false,null);
		return email;
	}

	//this method return email body and gets attachment
    public String DownloadSingleEmail(int msgNumber, boolean getAttach, String attachHome) {
        
        Folder inbox = Setup();
        String msg = null;
        try{
            try {
                inbox.open(Folder.READ_WRITE);
            }//inner try
            catch (MessagingException ex) {
                inbox.open(Folder.READ_ONLY);
            }//inner catch

            int totalMessages = inbox.getMessageCount();
            if (totalMessages == 0) {
                inbox.close(false);
                return msg;
            }//end if

            Message messsage = inbox.getMessage(msgNumber);
            msg = GetEmailBody(messsage);
			if (getAttach && attachHome != null) {
					MimeMessage tempMessage = (MimeMessage)messsage;
					GetEmailAttachment(tempMessage,attachHome);
			}//end if
            inbox.close(false);
        }//outer try
        catch (MessagingException ex) {
            ex.printStackTrace();
        }//outer catch
        return msg;
    }//end of DownloadEmail
    
    private String GetEmailBody(Message m) {
        String msgbody = "No messages in INBOX.";
        try {
            if (m == null) {
                return msgbody;
            }
            else {
				System.out.println("content type is "+m.getContentType());
                MimePart mp = (MimePart) m;
                if (mp.isMimeType("text/*")) {
                    // display message
                    msgbody = (String)mp.getContent();
                }//end if
                else {
                    if (mp.isMimeType("multipart/*")) {
                        // display multipart
                        Multipart multip = null;
                        multip = (Multipart)mp.getContent();
                        MimePart body = (MimePart) multip.getBodyPart(0);
                        msgbody = (String) body.getContent();
                    }
                }//end else multipart and rfc822
            }//end else
        }//end try
        catch (Exception e) {
            e.printStackTrace();
        }
        return msgbody;
    }//end EmailBody
    
    private void GetEmailAttachment(Message mymessage, String attachHome) {
        
        if (mymessage == null) {
            return;
        }
        else {
			try {
				MimeMessage tempMessage = (MimeMessage) mymessage;
				MimeMultipart mp = null;
				FileOutputStream fos = null;
				File tempFile = null;
				String rawData = null;
                if (tempMessage.isMimeType("multipart/*")) {
					mp = (MimeMultipart)tempMessage.getContent();
					for (int j=0, m=mp.getCount(); j<m; j++) {
						Part part = mp.getBodyPart(j);
						//System.out.println("file name is "+mp.getBodyPart(j).getFileName());
						String disposition = part.getDisposition();
						if (part.getFileName() != null) {
							//System.out.println("file name is "+part.getFileName());
							if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)))) {
								tempFile = new File(attachHome + part.getFileName());
								fos = new FileOutputStream(tempFile);
								//writes data in attachment to file
								MimePart codeStream = (MimePart)mp.getBodyPart(j);
								String encodingType = codeStream.getEncoding();
								InputStream is = codeStream.getInputStream();
								int c;
								int byteCount = 0;
								while ((c = is.read()) != -1) {
									fos.write(c);
									byteCount = byteCount + 1;
								}//end of while loop
							}//end inner if
						}//end outer if
					}//end inner for loop
				}//end if isMimeType
			}//end try
			catch (Exception e) {
				e.printStackTrace();
			}//end catch
        }//end else
    }//end EmailAttachment
    
}